package com.basiclib.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.basiclib.R


/**
 * @author Harisucici
 * @date 2017/11/1 0001
 */

class MyRecyclerView : androidx.recyclerview.widget.RecyclerView {

    private val defaultDivider = 0
    private var divider: Int = 0
    private val defaultTouch = true
    private var touch: Boolean = false

    lateinit var mLayoutManager: androidx.recyclerview.widget.LinearLayoutManager

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        handleAttrs(context, attrs)
        mLayoutManager  = androidx.recyclerview.widget.LinearLayoutManager(context)
        this.layoutManager = mLayoutManager
        this.setHasFixedSize(true)
        this.addItemDecoration(
            MyRecycleViewDivider(
                context, androidx.recyclerview.widget.LinearLayoutManager.VERTICAL, dp2px(context, divider.toFloat()),
                ContextCompat.getColor(context, R.color.gray_divider)
            )
        )
    }

    private fun handleAttrs(context: Context, attrs: AttributeSet) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.MyRecycler)
        divider = ta.getInt(R.styleable.MyRecycler_div, defaultDivider)
        touch = ta.getBoolean(R.styleable.MyRecycler_touch, defaultTouch)
        ta.recycle()
    }


    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        super.onMeasure(widthSpec, heightSpec)

    }

    override fun getLayoutManager(): androidx.recyclerview.widget.LinearLayoutManager? {
        return mLayoutManager
    }

    override fun onTouchEvent(ev: MotionEvent): Boolean {
        return if (!touch) {
            false
        } else super.onTouchEvent(ev)
    }

    fun MoveToPosition(n: Int) {
        mLayoutManager!!.scrollToPositionWithOffset(n, 0)
        mLayoutManager!!.stackFromEnd = true
    }

    fun MoveToPosition(mRecyclerView: androidx.recyclerview.widget.RecyclerView, n: Int) {
        val firstItem = mLayoutManager!!.findFirstVisibleItemPosition()
        val lastItem = mLayoutManager!!.findLastVisibleItemPosition()
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n)
        } else if (n <= lastItem) {
            val top = mRecyclerView.getChildAt(n - firstItem).top
            mRecyclerView.scrollBy(0, top)
        } else {
            mRecyclerView.scrollToPosition(n)
        }

    }

    fun dp2px(context: Context, dipValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dipValue * scale + 0.5f).toInt()
    }


    class MyRecycleViewDivider(context: Context, private val mOrientation: Int):
        androidx.recyclerview.widget.RecyclerView.ItemDecoration() {
        private var mPaint: Paint? = null
        private var mDivider: Drawable? = null
        private var mDividerHeight = 1

        init {
            if (mOrientation != androidx.recyclerview.widget.LinearLayoutManager.VERTICAL && mOrientation != androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL) {
                throw IllegalArgumentException("请输入正确的参数！")
            }

            val a = context.obtainStyledAttributes(ATTRS)
            mDivider = a.getDrawable(0)
            a.recycle()
        }

        /**
         * 自定义分割线
         *
         * @param context
         * @param orientation 列表方向
         * @param drawableId  分割线图片
         */
        constructor(context: Context, orientation: Int, drawableId: Int) : this(context, orientation) {
            mDivider = ContextCompat.getDrawable(context, drawableId)
            mDividerHeight = mDivider!!.intrinsicHeight
        }

        /**
         * 自定义分割线
         *
         * @param context
         * @param orientation   列表方向
         * @param dividerHeight 分割线高度
         * @param dividerColor  分割线颜色
         */
        constructor(context: Context, orientation: Int, dividerHeight: Int, dividerColor: Int) : this(
            context,
            orientation
        ) {
            mDividerHeight = dividerHeight
            mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
            mPaint!!.color = dividerColor
            mPaint!!.style = Paint.Style.FILL
        }


        //获取分割线尺寸
        override fun getItemOffsets(outRect: Rect, view: View, parent: androidx.recyclerview.widget.RecyclerView, state: androidx.recyclerview.widget.RecyclerView.State) {
            super.getItemOffsets(outRect, view, parent, state)
            outRect.set(0, 0, 0, mDividerHeight)
        }

        //绘制分割线
        override fun onDraw(c: Canvas, parent: androidx.recyclerview.widget.RecyclerView, state: androidx.recyclerview.widget.RecyclerView.State) {
            super.onDraw(c, parent, state)
            if (mOrientation == androidx.recyclerview.widget.LinearLayoutManager.VERTICAL) {
                drawVertical(c, parent)
            } else {
                drawHorizontal(c, parent)
            }
        }

        //绘制横向 item 分割线
        private fun drawHorizontal(canvas: Canvas, parent: androidx.recyclerview.widget.RecyclerView) {
            val left = parent.paddingLeft
            val right = parent.measuredWidth - parent.paddingRight
            val childSize = parent.childCount
            for (i in 0 until childSize) {
                val child = parent.getChildAt(i)
                val layoutParams = child.layoutParams as androidx.recyclerview.widget.RecyclerView.LayoutParams
                val top = child.bottom + layoutParams.bottomMargin
                val bottom = top + mDividerHeight
                if (mDivider != null) {
                    mDivider!!.setBounds(left, top, right, bottom)
                    mDivider!!.draw(canvas)
                }
                if (mPaint != null) {
                    canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), mPaint!!)
                }
            }
        }

        //绘制纵向 item 分割线
        private fun drawVertical(canvas: Canvas, parent: androidx.recyclerview.widget.RecyclerView) {
            val top = parent.paddingTop
            val bottom = parent.measuredHeight - parent.paddingBottom
            val childSize = parent.childCount
            for (i in 0 until childSize) {
                val child = parent.getChildAt(i)
                val layoutParams = child.layoutParams as androidx.recyclerview.widget.RecyclerView.LayoutParams
                val left = child.right + layoutParams.rightMargin
                val right = left + mDividerHeight
                if (mDivider != null) {
                    mDivider!!.setBounds(left, top, right, bottom)
                    mDivider!!.draw(canvas)
                }
                if (mPaint != null) {
                    canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), mPaint!!)
                }
            }
        }

        companion object {

            private val ATTRS = intArrayOf(android.R.attr.listDivider)
        }
    }

}

